from pymel.api import *
import maya.OpenMaya as om
import maya.cmds as cmd
from engine import *
import os

def Export(filepath):
    if "mb" in filepath:
        filepath.strip(".mb")
    
    fileloc = path.GetMayaFileLoc()

    # -- open maya file
    MFileIO.open(fileloc + "/" + filepath + ".mb")

    root = path.GetRoot()
    meshdir = os.path.join(root, "resources/mesh/")
    existence = os.path.isdir(meshdir)

    if not existence:
        print "%s does not exist!" % meshdir
        print "Exiting script."
        return -1
    else:
        outputfile = file(meshdir + "mesh.txt", "w")

    # -- create the mesh iterator
    meshiterator = om.MItDag(om.MItDag.kBreadthFirst, om.MFn.kMesh)

    # -- while there is still more to search
    while not meshiterator.isDone():
        # -- get the current node
        obj = meshiterator.currentItem()

        # -- print the name and write
        print meshiterator.partialPathName()
        outputfile.write(meshiterator.partialPathName() + "\n")

        # -- view node as mesh
        mesh = om.MFnMesh(obj)

        # -- create c arrays
        vertices = om.MFloatPointArray()
        vertcount = om.MIntArray()
        indices = om.MIntArray()

        # -- get the properties
        mesh.getPoints(vertices)
        mesh.getVertices(vertcount, indices)

        # -- write the properties to a file
        title = "Vertices: %s" % vertices.length()
        print title
        outputfile.write(title + "\n")
        for i in range(vertices.length()):
            output = "%f %f %f " % (vertices[i].x, vertices[i].y, vertices[i].z)
            print output
            outputfile.write(output + "\n")

        title = "Vertcount: %s" % vertcount.length()
        print title
        outputfile.write(title + "\n")
        for i in range(vertcount.length()):
            output = "%d" % (vertcount[i]) 
            print output
            outputfile.write(output + "\n")

        title = "Indices: %s" % indices.length()
        print title
        outputfile.write(title + "\n") 
        for i in range(indices.length()):
            output = "%d" % (indices[i]) 
            print "%d" % (indices[i])
            outputfile.write(output + "\n")

        # -- just for extra info print this too...
        current = 0
        for i in range(len(vertcount)):
            count = vertcount[i]
            print "from %d to %d " % (current, current + count)
            for j in range(current, current + count):
                print "%d, " % (indices[j])
                print "%f, %f, %f, " % (vertices[indices[j]].x, vertices[indices[j]].y, 
                                        vertices[indices[j]].z)
            current = current + count

        meshiterator.next()

    cmd.quit()
    
